package com.thd.springboottest.security.securitycustom;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登出处理器
 *
 * @author: wanglei62
 * @DATE: 2022/6/24 11:49
 **/
@Component("myLogoutHandler")
public class MyLogoutHandler implements LogoutHandler {
    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        System.out.println("登出成功后的处理");
        ObjectMapper json = new ObjectMapper();
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        try{
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication((Authentication)null);

            httpServletResponse.getWriter().write("登出成功");
        }catch(Exception e){
            throw new RuntimeException(e);
        }

    }
}
